<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="客户编号" prop="wid">
        <el-input
          v-model="queryParams.wid"
          placeholder="请输入客户编号"
          clearable
          @input="queryParams.wid = queryParams.wid.replace(/\D/g,'')"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户电话" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入客户电话"
          clearable
          @input="queryParams.phone = queryParams.phone.replace(/\D/g,'')"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户名称" prop="userNickName">
        <el-input
          v-model="queryParams.userNickName"
          placeholder="请输入客户名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户姓名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入客户姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户备注" prop="buyerRemark">
        <el-input
          v-model="queryParams.buyerRemark"
          placeholder="请输入客户备注"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['business:buyerInfo:add']"
        >获取</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['business:buyerInfo:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['business:buyerInfo:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['business:buyerInfo:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-upload2" size="mini" @click="handleImport" v-hasPermi="['business:buyerInfo:import']">导入</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="infoList" @selection-change="handleSelectionChange" border  height="650">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="序号"
        type="index"
        width="50"
        align="center"
        :index="(i) => (pageSize * (pageNum - 1)) + i + 1"
      />
      <el-table-column label="客户编号" align="center" prop="wid" />
      <el-table-column label="客户电话" align="center" prop="phone" />
      <el-table-column label="客户名称" align="center" prop="userNickName" />
      <el-table-column label="客户姓名" align="center" prop="name" />
      <el-table-column label="客户备注" align="center" prop="buyerRemark" show-overflow-tooltip/>
      <el-table-column label="创建人" align="center" prop="createBy" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180"  sortable>
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改人" align="center" prop="updateBy" />
      <el-table-column label="修改时间" align="center" prop="updateTime" width="180"  sortable>
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['business:buyerInfo:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['business:buyerInfo:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />


    <!-- 添加或修改客户信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="客户编号" prop="wid">
          <el-input v-model="form.wid"  :disabled="isEditMode" />
        </el-form-item>
        <el-form-item label="客户电话" prop="phone">
          <el-input v-model="form.phone"  :disabled="isEditMode" />
        </el-form-item>
        <el-form-item label="客户名称" prop="userNickName">
          <el-input v-model="form.userNickName" type="textarea"  :disabled="isEditMode" />
        </el-form-item>
        <el-form-item label="客户姓名" prop="name">
          <el-input v-model="form.name" type="textarea"  :disabled="isEditMode" />
        </el-form-item>
        <el-form-item label="客户备注" prop="buyerRemark">
          <el-input v-model="form.buyerRemark" type="textarea"  :autosize="{ minRows: 4, maxRows: 10 }" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="获取客户信息" :visible.sync="openOne" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px"  >
        <el-form-item label="客户编号" prop="wid">
          <el-input
            type="textarea"
            v-model="form.wid"
            :autosize="{ minRows: 4, maxRows: 10 }"
            placeholder="输入客户编号，最大支持一次查询 20 条，用逗号分隔"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormOne">确 定</el-button>
        <el-button @click="cancelOne">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url" :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import { listInfo, getInfo, delInfo, addInfo, updateInfo,fetchFromWeimob } from "@/api/business/buyerInfo";
  import { getToken } from '@/utils/auth'
  export default {
    name: "buyerInfo",
    data() {
      return {
        // 客户导入参数
        upload: {
          // 是否显示弹出层（客户信息导入）
          open: false,
          // 弹出层标题（客户信息导入）
          title: "",
          // 是否禁用上传
          isUploading: false,
          // 设置上传的请求头部
          headers: { Authorization: "Bearer " + getToken() },
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + '/business/buyerInfo/importBuyerInfoFile',
        },
        isEditMode: false, // ➤ 当前是否为编辑模式
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 客户信息表格数据
        infoList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        openOne:false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          wid:null,
          phone: null,
          userNickName: null,
          name:null,
          buyerRemark: null,
          createTime: null
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          wid: [
            { required: true, message: "客户编号不能为空", trigger: "blur" }
          ],
        },
        pageNum: 1,
        pageSize: 10,
      };
    },
    created() {
      this.getList();
    },
    methods: {
      // 点击导入按钮，打开导入弹窗
      handleImport() {
        this.upload.title = "客户信息导入";
        this.upload.open = true;
      },
      // 下载模板
      importTemplate() {
        this.download(
          '/business/buyerInfo/importTemplate',
          {},
          `客户导入_模版_${new Date().getTime()}.xlsx`
        );
      },
      // 文件上传过程中的处理
      handleFileUploadProgress(event, file, fileList) {
        this.upload.isUploading = true;
      },
      handleFileSuccess(response, file, fileList) {
        this.upload.open = false;
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
        const msg = response.message || response.msg || '导入完成';
        this.$alert(
          `<div style='overflow:auto;overflow-x:hidden;max-height:70vh;padding:10px 20px 0;'>${msg}</div>`,
          "导入结果",
          { dangerouslyUseHTMLString: true }
        );
        // 如果成功才刷新列表
        if (response.code === 200) {
          this.getList();
        }
      },

      // 提交上传表单，触发文件上传
      submitFileForm() {
        this.$refs.upload.submit();
      },
      /** 查询客户信息列表 */
      getList() {
        this.loading = true;
        listInfo(this.queryParams).then(response => {
          this.infoList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      cancelOne() {
        this.openOne = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          wid: null,
          phone: null,
          userNickName: null,
          name:null,
          buyerRemark: null,
          createTime: null,
          createBy: null,
          updateTime: null,
          updateBy: null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.wid)
        this.single = selection.length!==1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 --改为 从微盟获取客户信息  */
      handleAdd() {
        this.reset();
        this.openOne = true;
        this.title = "获取客户信息";
      },
      // handleAdd() {
      //   this.reset();
      //   this.open = true;
      //   this.isEditMode = false; // ➤ 新增
      //   this.title = "新增客户信息";
      // },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const wid = row.wid || this.ids
        getInfo(wid).then(response => {
          this.form = response.data;
          this.isEditMode = true; // ➤ 编辑模式
          this.open = true;
          this.title = "修改客户信息";
        });
      },
      /** 获取按钮 */
      submitFormOne() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            let rawInput = this.form.wid;

            // 替换中文逗号为英文逗号，并转为数字数组
            let widArray = rawInput
              .replace(/，/g, ',')
              .split(',')
              .map(item => item.trim())
              .filter(item => item !== '')
              .map(item => Number(item));

            // 验证格式
            if (widArray.some(isNaN)) {
              this.$modal.msgError("客户编号格式有误，请输入纯数字，并用英文逗号分隔");
              return;
            }

            // 去重
            let uniqueWids = [...new Set(widArray)];

            // 数量限制
            if (uniqueWids.length > 20) {
              this.$modal.msgError("最多只能查询 20 个客户编号");
              return;
            }

            // 调用接口
            fetchFromWeimob(uniqueWids).then(response => {
              this.$modal.msgSuccess("获取客户信息成功");
              this.openOne = false;
              this.getList();
            });
          }
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.isEditMode) {
              updateInfo(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addInfo(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const wids = row.wid || this.ids;
        this.$modal.confirm('是否确认删除客户信息编号为"' + wids + '"的数据项？').then(function() {
          return delInfo(wids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('business/buyerInfo/export', {
          ...this.queryParams
        }, `info_${new Date().getTime()}.xlsx`)
      }
    }
  };
</script>

<style >
  .el-table th {
    background-color: #e5e5e5 !important;
    color: #2c3e50;
    font-weight: bold;
  }
</style>
